﻿#include "player.h"
#include "ui_player.h"
#include"mypainer.h"

Player::Player(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Player),
    player(new QMediaPlayer(this)),
    playerlist(new QMediaPlaylist(this)),
    timer(new QTimer(this))
{
    ui->setupUi(this);
    this->movie=new QMovie(":/image/音乐.gif");
    ui->moive_label->setMovie(this->movie);//放置动态图
    ui->moive_label->setScaledContents(true);
    manager=new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));

    pModel=new QStandardItemModel(ui->tableView);//实例化模型，并指定模型依赖的控件
    ui->tableView->setModel(pModel);
    ui->tableView->setItemDelegateForColumn(4,new Mypainer);
    titles<<"歌名"<<"歌手"<<"专辑"<<"时长"<<"添加到播放列表";

    //tableview样式设计
    ui->tableView->setStyleSheet("QTableView { background-color: #f0f0f0; }");
    ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section { border: 1px solid #dcdcdc; }");
    ui->tableView->verticalHeader()->setStyleSheet("QHeaderView::section { border: 1px solid #dcdcdc; }");



    QStringList items;
    items << "顺序播放" << "随机播放" << "单曲循环";
    ui->paly_mode->addItems(items);
    ui->paly_mode->setCurrentIndex(0);  // 默认选择顺序播放
    ui->play_toolButton->setText("播放"); // 设置按钮的初始文本为“播放”

    //设置默认为列表循环播放
    this->playerlist->setPlaybackMode(QMediaPlaylist::Loop);

    connect(this->playerlist,&QMediaPlaylist::currentIndexChanged,this,[=](int ipos){
        ui->listWidget->setCurrentRow(ipos);
    });

    connect(ui->load_pushButton,&QPushButton::clicked,this,&Player::on_load_pushButton_clicked);//文件加载信号连接

    connect(ui->play_toolButton,&QPushButton::clicked,this,&Player::onPlayPauseButtonClicked);//播放与暂停按钮信号连接

    connect(ui->volume,&QSlider::valueChanged,this,&Player::on_volume_valueChanged);//音量滑块信号连接

    connect(ui->schedule,&QSlider::sliderMoved,this,&Player::on_schedule_sliderMoved);
    connect(player,&QMediaPlayer::positionChanged,this,&Player::on_postionChanged);
    connect(player,&QMediaPlayer::durationChanged,this,&Player::on_durationChanged);


    timer->setInterval(1000);
    connect(timer,&QTimer::timeout,this,&Player::updatePosition);
    timer->start();

    //标签设置
    ui->volume_label->setText(QString::number(ui->volume->value()));
    ui->start_label->setText("00:00");
    ui->total_label->setText("00:00");

    //滑块设置
    ui->schedule->setRange(0,player->duration()/1000);

    //设置播放器的播放列表
    player->setPlaylist(playerlist);
    this->playerlist->setPlaybackMode(QMediaPlaylist::Sequential);
}

Player::~Player()
{
    delete ui;
}


void Player::on_load_pushButton_clicked()
{
    QStringList  files=QFileDialog::getOpenFileNames(this,"选择音乐文件",":/music","音频文件 (*.mp3)");
    for(int i=0;i<files.size();i++)
    {
        QMediaContent mediaContent(QUrl::fromLocalFile(files[i]));
        this->playerlist->addMedia(mediaContent);
        QFileInfo info(files[i]);
        ui->listWidget->addItem(info.fileName());

//        player->setMedia(mediaContent);
        int duration=player->duration();//获取时长
        song _song;
        _song.songname=info.fileName();
        _song.duration2=duration/1000;
        song_list.push_back(_song);
    }

}
void Player::onPlayPauseButtonClicked()
{
    if(ui->play_toolButton->text()=="播放")
    {
        this->player->play();
        ui->play_toolButton->setText("暂停");
        //动图开始
        this->movie->start();
    }else if(ui->play_toolButton->text()=="暂停")
    {
        this->player->pause();
        ui->play_toolButton->setText("播放");
        //动图停止
        this->movie->stop();
    }
}

void Player::on_next_toolButton_clicked()
{
    this->playerlist->next();
    ui->play_toolButton->setText("暂停");
}

void Player::on_back_toolButton_clicked()
{
    this->playerlist->previous();
    ui->play_toolButton->setText("暂停");
}

void Player::on_paly_mode_currentTextChanged(const QString &arg1)
{
    if(arg1=="顺序播放")
    {
        this->playerlist->setPlaybackMode(QMediaPlaylist::Loop);
    }else if(arg1=="单曲循环")
    {
        this->playerlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }else if(arg1=="随机播放")
    {
        this->playerlist->setPlaybackMode(QMediaPlaylist::Random);
    }
}

void Player::on_listWidget_currentRowChanged(int currentRow)
{
    this->playerlist->setCurrentIndex(currentRow);
    this->player->play();
    ui->play_toolButton->setText("暂停");
    this->movie->start();//图片开始动
}

void Player::on_delete_pushButton_clicked()
{
    //删除两部分，播放列表和listwideget内的
    int index=ui->listWidget->currentRow();//获取选中的音乐索引
    if(this->playerlist->removeMedia(index))
    {
        ui->listWidget->takeItem(index);//删除listwidget内的选中选项
        this->player->pause();//歌曲暂停
        this->movie->stop();//图片暂停
        player->setPlaylist(playerlist);// 如果删除了当前正在播放的媒体，确保播放器使用播放列表
    }
}

void Player::replyFinished(QNetworkReply* reply)
{
    qDebug()<<"网页响应成功";
    QVariant ret= reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<"网页返回状态为"<<ret;
    if(ret==200)
    {
        QByteArray data=reply->readAll();//读取所有的网络数据
        parseJson(data);

    }
}

void Player::parseJson(QByteArray jsonByte)
{
    QString songname_original2;//歌名
    QString singername2;//歌手
    QString album_name2;//专辑
    int duration2;//时间
    int music_id;//音乐id
    QJsonParseError json_error;//json解析错误对象
    QJsonDocument parse_doucment=QJsonDocument::fromJson(jsonByte,&json_error);
    if(json_error.error==QJsonParseError::NoError)//判断解析过程是否有错
    {
        if(parse_doucment.isObject())//判断文档是否一个json对象
        {
            QJsonObject rootObj=parse_doucment.object();//获取文档json对象
            if(rootObj.contains("result"))//对象中是否包含键result
            {
                QJsonValue valuedata=rootObj.value("result");
                if(valuedata.isObject())//检查result对应的值是否是一个对象
                {
                    QJsonObject valuedataObject=valuedata.toObject();//把QJsonValue转为JsonObject对象
                    if(valuedataObject.contains("songs"))
                    {
                        QJsonValue valueArray=valuedataObject.value("songs");
                        if(valueArray.isArray())
                        {
                            //把结果转为QJsonArray数组才能遍历
                            QJsonArray array=valueArray.toArray();
                            int size=array.size();
                            for(int i=0;i<size;i++)
                            {
                                QJsonValue value=array.at(i);
                                if(value.isObject())
                                {
                                    //把数组的第一个元素变为JSON对象
                                    QJsonObject aobject=value.toObject();
                                    if(aobject.contains("album"))//专辑1
                                    {
                                        QJsonValue album_Object_1=aobject.value("album");
                                        if(album_Object_1.isObject())
                                        {
                                            QJsonObject album_Object_1_tmp=album_Object_1.toObject();
                                            if(album_Object_1_tmp.contains("name"))
                                            {
                                                QJsonValue ID_value=album_Object_1_tmp.value("name");
                                                if(ID_value.isString())
                                                {
                                                    album_name2=ID_value.toString();
                                                }
                                            }
                                        }
                                    }
                                    if(aobject.contains("artists"))//歌手
                                    {
                                        QJsonValue artists_value_tmp=aobject.value("artists");
                                        if(artists_value_tmp.isArray())
                                        {
                                            QJsonArray artist_array=artists_value_tmp.toArray();
                                            int artist_size=artist_array.size();
                                            for(int k=0;k<size;k++)
                                            {
                                                QJsonValue artists_name=artist_array.at(k);
                                                if(artists_name.isObject())
                                                {
                                                    QJsonObject artists_name_object=artists_name.toObject();
                                                    if(artists_name_object.contains("name"))
                                                    {
                                                        QJsonValue artistsname=artists_name_object.take("name");
                                                        if(artistsname.isString())
                                                        {
                                                            if(k==0)
                                                            {
                                                                singername2=artistsname.toString();
                                                            }else
                                                            {
                                                                singername2=singername2+"/"+artistsname.toString();
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if(aobject.contains("name"))//歌曲名
                                    {
                                        QJsonValue Album_ID_value=aobject.take("name");
                                        if(Album_ID_value.isString())
                                        {
                                            songname_original2=Album_ID_value.toString();
                                        }
                                    }
                                    if(aobject.contains("duration"))//时长
                                    {
                                        QJsonValue AlbumID_value=aobject.take("duration");
                                        duration2=AlbumID_value.toInt();
                                        duration2=duration2/1000;
                                    }
                                    if(aobject.contains("id"))//歌曲id
                                    {
                                        QJsonValue FileHash_value=aobject.take("id");
                                        if(!FileHash_value.isNull())
                                        {
                                            //用vector保存每首歌的album_id
                                            music_id=FileHash_value.toInt();
                                        }
                                    }
                                    song _song;
                                    _song.album_name=album_name2;
                                    _song.singer=singername2;
                                    _song.songname=songname_original2;
                                    _song.duration2=duration2;
                                    _song.music_id=music_id;
                                    song_list.push_back(_song);//保存歌曲信息
                                    pModel->setHorizontalHeaderLabels(titles);
                                    QString formattedDuration=formatDuration(duration2);

                                    QList<QStandardItem*>sti;
                                    sti<<new QStandardItem(songname_original2)<<new QStandardItem(singername2)<<new QStandardItem(album_name2)<<new QStandardItem(formattedDuration)<<new QStandardItem("未添加");
                                    pModel->appendRow(sti);
                                    //qDebug()<<album_name2<<" "<<singername2<<" "<<songname_original2<<" "<<duration2<<" "<<music_id;
                                }
                            }
                        }
                    }

                }

            }
        }
    }
    else
    {
        qDebug()<<json_error.errorString();
    }
    for(int i=0;i<song_list.size();i++)
    {
        song _song=song_list[i];
        qDebug()<<_song.album_name<<" "<<_song.singer<<" "<<_song.songname<<" "<<_song.duration2<<" "<<_song.music_id;
    }
}

QString Player::formatDuration(int durationInSeconds)//转换网易云内音乐的时间为分秒
{
    int minutes=durationInSeconds / 60;
    int seconds=durationInSeconds % 60;
    return QString("%1:%2").arg(minutes,2,10,QChar('0')).arg(seconds,2,10,QChar('0'));
}

void Player::on_grep_pushButton_clicked()
{
    QString key=ui->lineEdit->text();
    QString url=QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(key);
    manager->get(QNetworkRequest(QUrl(url)));
}

void Player::on_tableView_clicked(const QModelIndex &index)
{

    if (index.column() != 4)
        {
            return;
        }
        QVariant ret = pModel->data(index);
        QStandardItem *item = pModel->item(index.row(), index.column());
        delete item; // 释放原有选项
        int row = index.row(); // 获取当前点击的行号
        if (ret == "未添加")
        {
            // 获取歌曲信息
            if (row >= 0 && row < song_list.size()) // 修正行号检查为 >= 0
            {
                song selectedSong = song_list[row];
                QString play_url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(selectedSong.music_id);
                playerlist->addMedia(QMediaContent(QUrl(play_url)));
                ui->listWidget->addItem(selectedSong.songname);
                pModel->setItem(index.row(), index.column(), new QStandardItem("已添加"));

                if(!player->isMetaDataAvailable())
                {
                    connect(player,&QMediaPlayer::durationChanged,this,&Player::on_durationChanged);
                }
//                //获取时长lamb表达式
//                player->setMedia(QMediaContent(QUrl(play_url)));
//                connect(player, &QMediaPlayer::durationChanged, [this](qint64 duration) {
//                                int durationInSeconds = duration / 1000;
//                                ui->schedule->setRange(0, durationInSeconds); // 更新滑块范围
//                                ui->total_label->setText(formatDuration(durationInSeconds)); // 更新总时间标签
//                            });

            }
        }
        else if (ret == "已添加")
        {
            if (row >= 0 && row < song_list.size()) // 添加对 row 的检查
            {
                song selectedSong = song_list[row];

                // 从 QListWidget 中删除对应的歌曲项
                QList<QListWidgetItem *> items = ui->listWidget->findItems(selectedSong.songname, Qt::MatchExactly);
                if (!items.isEmpty())
                {
                    delete ui->listWidget->takeItem(ui->listWidget->row(items[0]));
                }

                // 在播放列表中查找并删除对应的歌曲项
                for (int i = 0; i < playerlist->mediaCount(); ++i)
                {
                    if (playerlist->media(i).canonicalUrl().toString().contains(QString::number(selectedSong.music_id)))
                    {
                        playerlist->removeMedia(i);
                        break; // 删除匹配项后退出循环
                    }
                }

                pModel->setItem(index.row(), index.column(), new QStandardItem("未添加"));
            }
        }
}

void Player::on_volume_valueChanged(int value)
{
    player->setVolume(value);// 设置音量
    QString labeText=QString("<img src=':/Icon/yinliang.svg' width='20' height='16'/> %1").arg(value);
    ui->volume_label->setText(labeText);
    //ui->volume_label->setText(QString::number(value));// 更新标签显示当前音量
}


void Player::on_schedule_sliderMoved(int position)
{
    player->setPosition(position*1000);// 将滑块位置设置为当前播放位置
}

void Player::on_postionChanged(qint64 position)
{
    ui->schedule->setValue(position / 1000); // 更新滑块位置
    ui->start_label->setText(formatDuration(position / 1000)); // 更新当前播放时间标签
}

void Player::on_durationChanged(qint64 duration)
{
    ui->schedule->setRange(0,duration/1000);
    ui->total_label->setText(formatDuration(duration/1000));// 更新总时间标签
}

void Player::updatePosition()
{
    qint64 position=player->position()/1000;// 获取当前播放位置（秒）
    ui->schedule->setValue(position);
    ui->start_label->setText(formatDuration(position));
}
